﻿using Spring.Context;
using Spring.Context.Support;
using System;
using System.Activities;
using System.Activities.DurableInstancing;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Runtime.DurableInstancing;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using XiDainChangAn.OA.BLL;
using XiDainChangAn.OA.IBLL;

namespace XiDainChangAn.OA.WF
{
    public class WorkflowApplicationHelper
    {
        private static readonly string _strConn = ConfigurationManager.ConnectionStrings["wfconn"].ConnectionString;


        #region 01，创建工作流+static WorkflowApplication CreateWorkflowApp(Activity activity, Dictionary<string, object> dic)
        /// <summary>
        /// 创建工作流
        /// </summary>
        /// <param name="activity"></param>
        /// <param name="dic"></param>
        /// <returns></returns>
        public static WorkflowApplication CreateWorkflowApp(Activity activity,int instanceId, Dictionary<string, object> dic)
        {
            AutoResetEvent syncEvent = new AutoResetEvent(false);
            //创建一个保存 工作流实例的sqlStore对象
            SqlWorkflowInstanceStore store = new SqlWorkflowInstanceStore(_strConn);
            WorkflowApplication wfApp;
            if (dic == null)
            {
                wfApp = new WorkflowApplication(activity);
            }
            else
            {
                wfApp = new WorkflowApplication(activity, dic);
            }

            //wfApp.Id//工作流实例id需要将此实例id保存到实例数据库中
            wfApp.InstanceStore = store;

            #region 工作流生命周期事件
            wfApp.Unloaded = delegate(WorkflowApplicationEventArgs er)
            {
                Console.WriteLine("工作流 {0} 卸载.", er.InstanceId);
            };
            wfApp.Completed = delegate(WorkflowApplicationCompletedEventArgs er)
            {
                Console.WriteLine("工作流 {0} 完成.", er.InstanceId);
                syncEvent.Set();
            };
            wfApp.Aborted = delegate(WorkflowApplicationAbortedEventArgs er)
            {
                Console.WriteLine("工作流 {0} 终止.", er.InstanceId);
            };
            wfApp.Idle = delegate(WorkflowApplicationIdleEventArgs er)
            {
                Console.WriteLine("工作流 {0} 空闲.", er.InstanceId);
                syncEvent.Set(); //这里要唤醒，不让的话，当创建了一个书签之后，界面就卡死了。
            };
            wfApp.PersistableIdle = delegate(WorkflowApplicationIdleEventArgs er)
            {
                Console.WriteLine("持久化");
                return PersistableIdleAction.Unload;
            };
            wfApp.OnUnhandledException = delegate(WorkflowApplicationUnhandledExceptionEventArgs er)
            {
                Console.WriteLine("OnUnhandledException in Workflow {0}\n{1}",
       er.InstanceId, er.UnhandledException.Message);
                return UnhandledExceptionAction.Terminate;
            };
            #endregion

            //根据流程id取得流程实例
            IApplicationContext ctx = ContextRegistry.GetContext();
            var WF_InstanceService = ctx.GetObject("WF_InstanceService") as IWF_InstanceService;

            var model = WF_InstanceService.GetEntitys(u => u.Id == instanceId).FirstOrDefault();
            model.WFInstanceId = wfApp.Id;
            WF_InstanceService.UpDate(model);

            wfApp.Run();
            //syncEvent.WaitOne();
            return wfApp;
        }
        #endregion

        public static WorkflowApplication ResumeBookMark(Activity activity, Guid instanceId, string bookName, object value)
        {
            AutoResetEvent syncEvent = new AutoResetEvent(false);
            //创建一个保存 工作流实例的sqlstore对象。
            SqlWorkflowInstanceStore store = new SqlWorkflowInstanceStore(_strConn);

            WorkflowApplication wfApp = new WorkflowApplication(activity);

            //wfApp在进行持久化的时候，保持到上面对象配置的数据库里面去
            wfApp.InstanceStore = store;

            #region 工作流生命周期事件
            wfApp.Unloaded = delegate(WorkflowApplicationEventArgs er)
            {
                Console.WriteLine("工作流 {0} 卸载.", er.InstanceId);
            };
            wfApp.Completed = delegate(WorkflowApplicationCompletedEventArgs er)
            {
                Console.WriteLine("工作流 {0} 完成.", er.InstanceId);
                syncEvent.Set();
            };
            wfApp.Aborted = delegate(WorkflowApplicationAbortedEventArgs er)
            {
                Console.WriteLine("工作流 {0} 终止.", er.InstanceId);
            };
            wfApp.Idle = delegate(WorkflowApplicationIdleEventArgs er)
            {
                Console.WriteLine("工作流 {0} 空闲.", er.InstanceId);
                syncEvent.Set(); //这里要唤醒，不让的话，当创建了一个书签之后，界面就卡死了。
            };
            wfApp.PersistableIdle = delegate(WorkflowApplicationIdleEventArgs er)
            {
                Console.WriteLine("持久化");
                return PersistableIdleAction.Unload;
            };
            wfApp.OnUnhandledException = delegate(WorkflowApplicationUnhandledExceptionEventArgs er)
            {
                Console.WriteLine("OnUnhandledException in Workflow {0}\n{1}",
       er.InstanceId, er.UnhandledException.Message);
                return UnhandledExceptionAction.Terminate;
            };
            #endregion


            //从数据库加载当前的工作实例的状态
            wfApp.Load(instanceId);
            //让工作流沿着Demo书签位置继续往下执行
            wfApp.ResumeBookmark(bookName, value);
            return wfApp;

        }

    }
}
